﻿#include"slist.h"

// 动态申请一个节点
SListNode* BuySListNode(SLTDateType x)
{
	SListNode* newnode = (SListNode*)malloc(sizeof(SListNode) * 1);
	if (newnode == NULL)
	{
		printf("malloc fail!\n");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}

// 单链表打印
void SListPrint(SListNode* plist)
{
	while (plist != NULL)
	{
		printf("%d->", plist->data);
		plist = plist->next;
	}
	printf("NULL\n");
}

// 单链表尾插
void SListPushBack(SListNode** pplist, SLTDateType x)
{
	assert(pplist);
	SListNode* newnode = BuySListNode(x);
	SListNode* temp = *pplist;
	if (temp == NULL)
	{
		*pplist = newnode;
	}
	else
	{
		while (temp->next != NULL)
		{
			temp = temp->next;
		}
		temp->next = newnode;
	}
}

// 单链表的头插
void SListPushFront(SListNode** pplist, SLTDateType x)
{
	assert(pplist);
	SListNode* newnode = BuySListNode(x);
	newnode->next = *pplist;
	*pplist = newnode;
}

// 单链表的尾删
void SListPopBack(SListNode** pplist)
{
	assert(*pplist != NULL);
	SListNode* temp = *pplist;
	if (temp->next == NULL)
	{
		free(temp);
		*pplist = NULL;
	}
	else
	{
		SListNode* prev = *pplist;
		while (temp->next != NULL)
		{
			prev = temp;
			temp = temp->next;
		}
		free(prev->next);
		prev->next = NULL;
	}
}

// 单链表头删
void SListPopFront(SListNode** pplist)
{
	assert(*pplist != NULL);
	SListNode* temp = *pplist;
	*pplist = (*pplist)->next;
	free(temp);
}

// 单链表查找
SListNode* SListFind(SListNode* plist, SLTDateType x)
{
	assert(plist != NULL);
	SListNode* temp = plist;
	while (temp != NULL)
	{
		if (x == temp->data)
		{
			return temp;
		}
		temp = temp->next;
	}
	return NULL;
}

// 单链表在pos位置之后插入x
// 分析思考为什么不在pos位置之前插入？
void SListInsertAfter(SListNode* pos, SLTDateType x)
{
	assert(pos != NULL);
	SListNode* newnode = BuySListNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}

// 单链表删除pos位置之后的值
// 分析思考为什么不删除pos位置？
void SListEraseAfter(SListNode* pos)
{
	assert(pos != NULL);
	assert(pos->next != NULL);
	pos->next = pos->next->next;
}

// 在pos的前面插入
void SLTInsert(SListNode** pphead, SListNode* pos, SLTDateType x)
{
	assert(*pphead != NULL);
	assert(pos != NULL);
	SListNode* newnode = BuySListNode(x);
	SListNode* temp = *pphead;
	if (pos==temp)
	{
		newnode->next = pos;
		*pphead = newnode;
	}
	else
	{
		while (temp->next != pos)
		{
			temp = temp->next;
		}
		newnode->next = temp->next;
		temp->next = newnode;
	}
}

// 删除pos位置
void SLTErase(SListNode** pphead, SListNode* pos)
{
	assert(*pphead != NULL);
	assert(pos != NULL);
	SListNode* temp = *pphead;
	if (temp == pos)
	{
		*pphead = pos->next;
		free(pos);
	}
	else
	{
		while (temp->next != pos)
		{
			temp = temp->next;
		}
		temp->next = pos->next;
		free(pos);
	}
}

//释放
void SLTDestroy(SListNode** pphead)
{
	assert(pphead && *pphead);
	SListNode* temp = *pphead;
	while (temp != NULL)
	{
		SListNode* next = temp->next;
		free(temp);
		temp = next;
	}
	*pphead = NULL;
}
